<?php

namespace app\http\middleware;

use lib\builtin\auth\NoPermissionException;

class CheckAuth
{
    const LOGIN = -1;

    private $skip = false;

    public function __construct()
    {
        $this->skip = config('app.skip_auth');
    }

    /**
     * @param string $code 权限代码
     */
    public function handle($request, \Closure $next, $code)
    {
        $result = $this->check($code);
        if ($result === true) {
            return $next($request);
        } else {
            error($result[0], $result[1]);
        }
    }

    public function can($code)
    {
        return $this->check($code) === true;
    }

    protected function check($code)
    {
        if ($this->skip) {
            return true;
        }

        $user = \getCurrentUser();

        // 检查是否登录
        if (!$user) {
            return ['您未登录', 401];
        }

        // 检查是否可用
        if (!$user->is_active) {
            return ['您的账户已停用', 403];
        }

        if ($code === self::LOGIN) {
            return true;
        }

        // 是否是超级管理员
        if ($user->is_superadmin) {
            return true;
        }

        try {
            // 检查是否具有权限
            $user->needPermission($code);
            return true;
        } catch (NoPermissionException $e) {
            return [$e->getMessage(), 403];
        }
    }
}
